package com.ocp.macro.utils;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.ocp.macro.enums.DataCode;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * json数据转换
 */
@Slf4j
public class GsonUtils {

    private static Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();

    public static String toJson(Object obj) {
        return gson.toJson(obj);
    }

    public static <T> T toBean(String jsonStr, Class<T> objClass) {
        try{
            return gson.fromJson(jsonStr, objClass);
        }catch (Exception e){
            log.error(e.toString());

            return null;
        }
    }

    public static Object resultData(Object object){
        try {
           return toJson(object);
        }catch (Exception e){
            log.error(e.toString());
            Map<String, Object> map = new HashMap<>();
            map.put("code", DataCode.FAIL.getCode());
            map.put("message", DataCode.FAIL.getMessage());
            return map;
        }
    }

    /**
     * 获取request中json数据对象
     * @param request HttpServletRequest
     * @return json数据对象
     */
    public static JSONObject getParameters(HttpServletRequest request){
        BufferedReader bReader = null;
        InputStreamReader isr = null;
        try {
            InputStream iis = request.getInputStream();
            isr = new InputStreamReader(iis, StandardCharsets.UTF_8);
            bReader = new BufferedReader(isr);
            String str = null;
            StringBuilder buffer = new StringBuilder();

            while ((str = bReader.readLine()) != null) {
                buffer.append(str).append("\n");
            }

            log.info(buffer.toString());

            return JSONObject.parseObject(buffer.toString());
        } catch (IOException e) {
            log.error("解析request的json数据出错："+e.toString());
        } finally{
            try {
                if (bReader!=null)
                    bReader.close();
            } catch (IOException e) {
                log.error("关闭BufferedReader流出错："+e.toString());
            }
            try {
                if (isr!=null)
                    isr.close();
            } catch (IOException e) {
                log.error("关闭InputStreamReader流出错："+e.toString());
            }
        }
        return new JSONObject();
    }

    /**
     * json字符串转成JSONObject对象
     * @param jsonStr json字符串
     * @return JSONObject对象
     */
    public static JSONObject toJsonObject(String jsonStr){
        if (jsonStr==null) return new JSONObject();
        return JSONObject.parseObject(jsonStr);
    }

    /**
     * @param json list的序列化字符串
     * @param <T>  T类型
     * @return List<T>
     */
    public static <T> List<T> toList(String json, Class<T> clazz) {
        return gson.fromJson(json, TypeToken.getParameterized(List.class, clazz).getType());
    }

//    public static void main(String[] args) {
//        String jsonStr = "{\"alctProduct\":[{\"inPlaceName\":\"asdf\",\"inDepsStock\":23,\"alctProNum\":12},{\"inPlaceName\":\"asdf\",\"inDepsStock\":23,\"alctProNum\":12}]}";
//        JSONObject jsonObject = toJsonObject(jsonStr);
//        String strList = jsonObject.getString("alctProduct");
//        List<AlctProduct> list = toList(strList, AlctProduct.class);
//        System.out.println(list.get(0).toString());
//    }

}
